package org.unt.genlogic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class StringLogic {

	public static void main(String[] args) throws IOException {
		
		URL url = ClassLoader.getSystemResource("log4j.properties");
		System.out.println(url);

		if (true) return;
		
		List list = loadFileToList("log4j.properties");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(i + "\t" + list.get(i));
		}
	}

	public static String to2Tabs(String str) {
		return toTabs(str, 2);
	}

	public static String toTabs(String str, int n) {

		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < n; i++) {
			buf.append("    ");
		}

		return (str + buf.toString()).substring(0, buf.length());
	}

	public static Properties load(String propsName) throws Exception {

		Properties props = new Properties();
		URL url = ClassLoader.getSystemResource(propsName);

		InputStream is = url.openStream();
/*
		if (url != null) {
			is = url.openStream();
		} else {
			is = "".getClass().getClassLoader().getResourceAsStream(propsName);
		}
*/
		props.load(is);

		return props;
	}

	public static List loadFileToList(String fileToRead) throws IOException {

		URL url = ClassLoader.getSystemResource(fileToRead);
		String filePath = url.getFile();

		File file = new File(filePath);
		FileReader reader = new FileReader(file);
		BufferedReader b = new BufferedReader(reader);

		List list = new ArrayList();
		String line;
		while ((line = b.readLine()) != null) {
			list.add(line);
		}

		return list;
	}

	public static String duplicateSinglesQuotes(String str) {

		if (str == null || str.trim().equals("")) {
			return str;
		}

		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {

			if (str.charAt(i) != '\'') {
				buf.append(str.charAt(i));
			} else {
				buf.append('\'');
				buf.append('\'');
			}
		}

		return buf.toString();
	}

	public static String stringToFixedWidth(String str, int width, boolean rightOriented) {

		if (str == null) {
			str = "";
		}

		// TODO Improve this
		StringBuffer blanks = new StringBuffer();
		while (blanks.length() < width) {
			blanks.append("          ");
		}

		if (rightOriented) {

			str = blanks.toString() + str;
			return str.substring(str.length() - width);

		} else {

			str = str + blanks.toString();
			return str.substring(0, width);

		}
	}
}
